﻿using DeviceMaintainGIS.Entity;
using DeviceMaintainGIS.Model;
using DeviceMaintainGIS.Model.Remote;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace DeviceMaintainGIS.BLL.Remote
{
    /// <summary>
    /// 远程服务操作类
    /// </summary>
    public class RemoteService
    {
        /// <summary>
        /// 根据条件查询远程服务信息表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ReturnListVM<RemoteResponse> GetRemoteList(RemoteSelectRequest request)
        {
            ReturnListVM<RemoteResponse> list = new ReturnListVM<RemoteResponse>();

            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                var linq = from k in Entities.RepairRelation_Tab
                           join f in Entities.Remote_Tab on k.RelationGuid equals f.Guid
                           into tmpRepair
                           //let a = tmpRepair.FirstOrDefault()
                           from a in tmpRepair.DefaultIfEmpty()
                           join u in Entities.FieldInfo_Tab on k.RelationGuid equals u.RRGuid
                           into tmpFieldInfo
                           from b in tmpFieldInfo.DefaultIfEmpty()
                           join ur in Entities.tbUser on k.OperatorID equals ur.ID
                           into tmptbUser
                           from tbUser in tmptbUser.DefaultIfEmpty()
                           select new RemoteResponse
                           {
                               Guid = a.Guid,
                               RepairId = a.RepairId,
                               ServiceType = a.ServiceType,
                               Support = a.Support,
                               FixUp = a.FixUp,
                               Remark = a.Remark,
                               RepairOrChange = a.RepairOrChange,
                               OperatorID = k.OperatorID,
                               Feedback = a.Feedback,
                               AddTime = a.AddTime,
                               Step = k.Step,
                               State = k.State,
                               userIDs = b == null ? "" : b.userIDs,
                               PlateNumber = b == null ? "" : b.PlateNumber,
                               SceneTime = b == null ? System.DateTime.Now : b.SceneTime,
                               EndTime = b == null ? System.DateTime.Now : b.EndTime,
                               OperatorName = tbUser == null ? "" : tbUser.RealName,
                           };
                //报修编号查询条件
                if (!string.IsNullOrEmpty(request.RepairId))
                {
                    linq = linq.Where(i => i.RepairId == request.RepairId);
                }
                //操作人查询条件
                if (request.OperatorID != -1)
                {
                    linq = linq.Where(i => i.OperatorID == request.OperatorID);
                }
                //步骤查询条件
                if (request.Step != -1)
                {
                    linq = linq.Where(i => i.Step == request.Step);
                }
                //报修编号查询条件
                if (!string.IsNullOrEmpty(request.RelationGuid))
                {
                    linq = linq.Where(i => i.Guid == request.RelationGuid);
                }
                list.TotalCount = linq.Count();
                List<RemoteResponse> RemoteResponseList = linq.OrderByDescending(i => i.AddTime).Take(request.PagesSize * request.PageIndex).Skip(request.PagesSize * (request.PageIndex - 1)).ToList();
                list.List = RemoteResponseList;
                list.PageIndex = request.PageIndex;
                list.PagesSize = request.PagesSize;
            }
            return list;
        }
        /// <summary>
        /// 添加远程服务
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ReturnMessageVM RemoteAdd(RemoteRequest request)
        {
            //下一步操作人
            //int NextOperatorID = -1;
            ReturnMessageVM rm = new ReturnMessageVM();
            rm.Succeed = true;
            //远程服务表
            string newID = Guid.NewGuid().ToString();
            Remote_Tab rt = new Remote_Tab();
            rt.Guid = newID;
            rt.RepairId = request.RepairId;
            rt.ServiceType = request.ServiceType;
            rt.Support = request.Support;
            rt.FixUp = request.FixUp;
            rt.Remark = request.Remark;
            rt.RepairOrChange = request.RepairOrChange;
            rt.Feedback = request.Feedback;
            rt.State = request.State;
            rt.AddTime = System.DateTime.Now;

            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                using (TransactionScope transaction = new TransactionScope())
                {
                    try
                    {
                        Entities.Remote_Tab.Add(rt);
                        Entities.Entry<Remote_Tab>(rt).State = System.Data.Entity.EntityState.Added;
                        //出现场信息 2 不出现场 1 出现场
                        if (request.FixUp == 1)
                        {
                            //出现场信息表
                            FieldInfo_Tab fi = new FieldInfo_Tab();
                            fi.RRGuid = newID;
                            string stuserIDs = "";
                            for (int i = 0; i < request.userIDs.Count(); i++)
                            {
                                stuserIDs += request.userIDs[i] + ",";
                            }
                            fi.userIDs = stuserIDs;
                            fi.PlateNumber = request.PlateNumber;
                            fi.SceneTime = System.DateTime.Now;
                            fi.EndTime = request.EndTime;
                            Entities.FieldInfo_Tab.Add(fi);
                            Entities.Entry<FieldInfo_Tab>(fi).State = System.Data.Entity.EntityState.Added;

                            //NextOperatorID = request.userIDs[0];
                        }
                        //else
                        //{
                        //    NextOperatorID = request.
                        //}
                        //查询上一步操作 更新其状态为已完成

                        RepairRelation_Tab stepRepairRelation = Entities.RepairRelation_Tab.Where(i => i.RepairId == request.RepairId && i.Step == (request.Step - 1) && i.State == 0).FirstOrDefault();
                        if (stepRepairRelation != null && request.State != 0)
                        {
                            stepRepairRelation.State = 1;
                            Entities.RepairRelation_Tab.Add(stepRepairRelation);
                            Entities.Entry<RepairRelation_Tab>(stepRepairRelation).State = System.Data.Entity.EntityState.Modified;
                        }


                        //报修关系表
                        RepairRelation_Tab rrt = new RepairRelation_Tab();

                        rrt.RepairId = request.RepairId;
                        rrt.AddTime = System.DateTime.Now;
                        rrt.TableName = "Remote_Tab";
                        rrt.RelationGuid = newID;
                        rrt.Step = request.Step;
                        rrt.OperatorID = request.OperatorID;
                        rrt.NextOperatorID = request.NextOperatorID;
                        //结束流程
                        if (request.State == -1)
                        {
                            rrt.State = 1;
                            rrt.Operator = -1;
                            rrt.TableName = "RepairEnd_Tab";
                            //报修结束表
                            RepairEnd_Tab ret = new RepairEnd_Tab();
                            ret.Guid = Guid.NewGuid().ToString();
                            ret.RepairId = request.RepairId;
                            ret.EndTime = System.DateTime.Now;
                            Entities.RepairEnd_Tab.Add(ret);
                            Entities.Entry<RepairEnd_Tab>(ret).State = System.Data.Entity.EntityState.Added;
                        }
                        else
                        {
                            rrt.State = request.State == 1 ? 0 : 2;
                            //如果不去现场 又不结束 流程直接到维修换新
                            if (request.FixUp == 1)
                            {
                                rrt.Operator = 3;
                            }
                            else
                            {
                                rrt.Operator = 4;
                            }
                        }

                        Entities.RepairRelation_Tab.Add(rrt);
                        Entities.Entry<RepairRelation_Tab>(rrt).State = System.Data.Entity.EntityState.Added;

                        rm.Message = newID;

                        Entities.SaveChanges();
                        //提交事务
                        transaction.Complete();
                    }
                    catch (Exception ex)
                    {
                        rm.Succeed = false;
                        rm.Message = "入库失败";
                    }
                }
            }


            return rm;
        }
        /// <summary>
        /// 编辑远程服务
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ReturnMessageVM RemoteEdit(RemoteRequest request)
        {
            //下一步操作人
            //int NextOperatorID = -1;
            ReturnMessageVM rm = new ReturnMessageVM();
            rm.Succeed = true;
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                using (TransactionScope transaction = new TransactionScope())
                {
                    try
                    {
                        //获取远程服务表信息
                        Remote_Tab RemoteTab = Entities.Remote_Tab.Where(i => i.Guid == request.RelationGuid).FirstOrDefault();
                        if (RemoteTab == null)
                        {
                            rm.Succeed = false;
                            rm.Message = "无远程服务信息";
                        }
                        rm.Message = RemoteTab.Guid;
                        RemoteTab.RepairId = request.RepairId;
                        RemoteTab.ServiceType = request.ServiceType;
                        RemoteTab.Support = request.Support;
                        RemoteTab.FixUp = request.FixUp;
                        RemoteTab.Remark = request.Remark;
                        RemoteTab.RepairOrChange = request.RepairOrChange;
                        RemoteTab.Feedback = request.Feedback;
                        RemoteTab.State = request.State;
                        RemoteTab.AddTime = System.DateTime.Now;

                        Entities.Remote_Tab.Add(RemoteTab);
                        Entities.Entry<Remote_Tab>(RemoteTab).State = System.Data.Entity.EntityState.Modified;
                        //出现场信息 2 不出现场 1 出现场
                        if (request.FixUp == 2)
                        {
                            //出现场信息表
                            FieldInfo_Tab fi = Entities.FieldInfo_Tab.Where(i => i.RRGuid == request.RelationGuid).FirstOrDefault();
                            if (fi != null)
                            {
                                Entities.FieldInfo_Tab.Add(fi);
                                Entities.Entry<FieldInfo_Tab>(fi).State = System.Data.Entity.EntityState.Deleted;
                            }
                        }
                        else
                        {
                            //出现场信息表
                            FieldInfo_Tab fi = Entities.FieldInfo_Tab.Where(i => i.RRGuid == request.RelationGuid).FirstOrDefault();
                            //如果为空添加出现场信息 不为空编辑出现场信息
                            if (fi == null)
                            {
                                fi = new FieldInfo_Tab();
                                fi.RRGuid = request.RelationGuid;
                                string stuserIDs = "";
                                for (int i = 0; i < request.userIDs.Count(); i++)
                                {
                                    stuserIDs += request.userIDs[i] + ",";
                                }
                                fi.userIDs = stuserIDs;
                                fi.PlateNumber = request.PlateNumber;
                                fi.SceneTime = System.DateTime.Now;
                                fi.EndTime = request.EndTime;
                                Entities.FieldInfo_Tab.Add(fi);
                                Entities.Entry<FieldInfo_Tab>(fi).State = System.Data.Entity.EntityState.Added;
                            }
                            else
                            {
                                string stuserIDs = "";
                                for (int i = 0; i < request.userIDs.Count(); i++)
                                {
                                    stuserIDs += request.userIDs[i] + ",";
                                }
                                fi.userIDs = stuserIDs;
                                fi.PlateNumber = request.PlateNumber;
                                fi.SceneTime = System.DateTime.Now;
                                fi.EndTime = request.EndTime;
                                Entities.FieldInfo_Tab.Add(fi);
                                Entities.Entry<FieldInfo_Tab>(fi).State = System.Data.Entity.EntityState.Modified;
                            }
                            ////NextOperatorID = int.Parse(request.userIDs.Split(',')[0]);
                            //NextOperatorID = request.userIDs[0];
                        }
                        //上一级保修关系更改
                        RepairRelation_Tab stepRepairRelation = Entities.RepairRelation_Tab.Where(i => i.RepairId == request.RepairId && i.Step == (request.Step - 1) && i.State == 0).FirstOrDefault();
                        if (stepRepairRelation != null && request.State != 0)
                        {
                            stepRepairRelation.State = 1;
                            Entities.RepairRelation_Tab.Add(stepRepairRelation);
                            Entities.Entry<RepairRelation_Tab>(stepRepairRelation).State = System.Data.Entity.EntityState.Modified;
                        }

                        //报修关系表
                        RepairRelation_Tab RepairRelationTab = Entities.RepairRelation_Tab.Where(i => i.RelationGuid == request.RelationGuid).FirstOrDefault();

                        RepairRelationTab.AddTime = System.DateTime.Now;
                        RepairRelationTab.OperatorID = request.OperatorID;
                        RepairRelationTab.NextOperatorID = request.NextOperatorID; //NextOperatorID;
                        RepairRelationTab.Step = request.Step;
                        //结束流程
                        if (request.State == -1)
                        {
                            RepairRelationTab.State = 1;
                            RepairRelationTab.Operator = -1;
                            RepairRelationTab.TableName = "RepairEnd_Tab";
                            //报修结束表
                            RepairEnd_Tab ret = new RepairEnd_Tab();
                            ret.Guid = Guid.NewGuid().ToString();
                            ret.RepairId = request.RepairId;
                            ret.EndTime = System.DateTime.Now;
                            Entities.RepairEnd_Tab.Add(ret);
                            Entities.Entry<RepairEnd_Tab>(ret).State = System.Data.Entity.EntityState.Added;
                        }
                        else
                        {
                            RepairRelationTab.State = request.State == 1 ? 0 : 2;

                            //如果不去现场 又不结束 流程直接到维修换新
                            if (request.FixUp == 1)
                            {
                                RepairRelationTab.Operator = 3;
                            }
                            else
                            {
                                RepairRelationTab.Operator = 4;
                            }
                        }

                        Entities.RepairRelation_Tab.Add(RepairRelationTab);
                        Entities.Entry<RepairRelation_Tab>(RepairRelationTab).State = System.Data.Entity.EntityState.Modified;


                        //提交保存
                        Entities.SaveChanges();
                        //提交事务
                        transaction.Complete();
                    }
                    catch (Exception ex)
                    {
                        rm.Succeed = false;
                        rm.Message = "入库失败";
                    }
                }
            }
            return rm;
        }
        /// <summary>
        /// 远程服务操作
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ReturnMessageVM RemoteOperation(RemoteRequest request)
        {
            ReturnMessageVM rm = new ReturnMessageVM();
            if (string.IsNullOrEmpty(request.RelationGuid))
            {
                rm = RemoteAdd(request);
            }
            else
            {
                rm = RemoteEdit(request);
            }
            return rm;
        }
    }
}
